<template>
  <a-card>
    <a-row :gutter="[16, 16]">
      <a-col :span="8">
        <Info label="我的昵称">{{ getUserInfo.nickname }}</Info>
      </a-col>
      <a-col :span="8">
        <Info label="我的ID">{{ getUserInfo.id }}</Info>
      </a-col>
      <a-col :span="8">
        <Info label="收款地址">
          {{ getUserInfo.payment_address }}
        </Info>
      </a-col>

      <a-col :span="8">
        <Info label="我的账号">{{ getUserInfo.username }}</Info>
      </a-col>
      <a-col :span="8">
        <Info label="级别">{{ getUserInfo.level }}</Info>
      </a-col>
      <a-col :span="8">
        <Info label="团队号">{{ getUserInfo.team }}</Info>
      </a-col>

      <a-col :span="8">
        <Info label="余额"
          ><span style="color: #f50">{{ getUserInfo?.balance?.balance }}</span></Info
        >
      </a-col>
      <a-col :span="8">
        <Info label="押金">
          <span style="color: #f50">{{ getUserInfo?.balance?.freezeMoney }}</span>
        </Info>
      </a-col>
      <a-col :span="8">
        <Info label="注册时间">{{
          dayjs(getUserInfo.create_time * 1000).format('YYYY-MM-DD HH:mm:ss')
        }}</Info>
      </a-col>
    </a-row>
  </a-card>

  <a-card title="余额充值">
    <a-row :gutter="16">
      <a-col :span="20">
        <a-form>
          <a-form-item label="充值类型" :rules="[{ required: true, message: '请选择充值类型' }]">
            <a-select
              v-model:value="formState.type"
              :fieldNames="{ label: 'title', value: 'id' }"
              :options="payList"
              @change="handlePaymentTypeChange"
            />
          </a-form-item>
          <a-form-item v-if="showFl" style="margin-right: 60px; margin-bottom: -24px">
            <fL
              :rate="getSiteConfig.rate.rate"
              :surcharge="getSiteConfig.rate.surcharge"
              :amount="formState.amount"
            />
          </a-form-item>
          <a-form-item label="充值金额" :rules="[{ required: true, message: '请输入充值金额' }]">
            <a-input-number v-model:value="formState.amount" />
          </a-form-item>
        </a-form>
      </a-col>
      <a-col :span="4">
        <a-button type="primary" @click="payFunc">点我充值</a-button>
      </a-col>
    </a-row>
  </a-card>

  <a-card title="代理互转">
    <a-row :gutter="16">
      <a-col :span="20">
        <BasicForm @register="registerRechargeForm" />
      </a-col>
      <a-col :span="4">
        <a-button type="primary" @click="inputPaymenPwd">点我转账</a-button>
      </a-col>
    </a-row>

    <PayCodeModal @register="registerPayModal" />
  </a-card>
</template>

<script setup lang="ts">
  import Info from '../components/info.vue';
  import PayCodeModal from '../modal/payCode.vue';
  import { useUserStore } from '@/store/modules/user';
  import dayjs from 'dayjs';
  import { payApi, interchangeApi, getPayListApi, GetInfoApi } from '@/api/user/index';
  import { useModal } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { createPrompt } from '@/components/Prompt';
  import fL from './fL.vue';
  import { ref, onMounted, onUnmounted } from 'vue';
  import { Modal } from 'ant-design-vue';

  const { getUserInfo, getSiteConfig, refreshBalance } = useUserStore();
  const [registerPayModal, { openModal: openPayModal }] = useModal();
  const payList = ref([]);
  const formState = ref({
    type: '',
    amount: 0,
  });
  const showFl = ref(false);
  const balance = ref({
    freezeTrade: 0,
    balance: 0,
    freezeMoney: 0,
  });
  let timer;

  onMounted(() => {
    getPayListApi().then((res) => {
      payList.value = res;
    });
    timer = setInterval(() => {
      refreshBalanceFunc();
    }, 5000);
  });

  onUnmounted(() => {
    clearInterval(timer);
  });

  async function refreshBalanceFunc() {
    balance.value = await refreshBalance();
  }

  const [
    registerRechargeForm,
    { validate: validateRechargeForm, getFieldsValue: getFieldsValueRecharge },
  ] = useForm({
    labelWidth: 100,
    schemas: [
      {
        field: 'payment_address',
        component: 'Input',
        label: '转账接收地址',
        colProps: {
          span: 24,
        },
        componentProps: {
          placeholder: '请输入转账接收地址',
        },
        rules: [{ required: true, message: '请输入转账接收地址' }],
      },
      {
        field: 'amount',
        component: 'Input',
        label: '转出金额',
        colProps: {
          span: 24,
        },
        componentProps: {
          placeholder: '请输入转出金额',
        },
        rules: [{ required: true, message: '请输入转出金额' }],
      },
    ],
    showActionButtonGroup: false,
  });

  const getPayType = (id) => {
    return payList.value.filter((item) => item.id == id);
  };

  const payFunc = () => {
    const params = {
      id: formState.value.type,
      amount: formState.value.amount,
    };
    const item = getPayType(params.id);
    payApi(params).then((res) => {
      openPayModal(true, { info: res, type: item[0].auto, payment_t: item[0].title });
    });
  };

  const inputPaymenPwd = () => {
    validateRechargeForm().then(() => {
      createPrompt({
        title: '请输入支付密码',
        required: true,
        label: '支付密码',
        defaultValue: '',
        onOK: async (password: string) => {
          Modal.info({
            content: `您是否要转账 ${getFieldsValueRecharge().amount} 元给 ${getFieldsValueRecharge().payment_address} `,
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
              return new Promise((resolve) => {
                interchangeFunc(password);
                resolve(true);
              });
            },
          });
        },
        inputType: 'Input',
      });
    });
  };

  const handlePaymentTypeChange = (val, option) => {
    // 判断字段是否包含USDT
    showFl.value = option.title.includes('USDT');
    if (showFl.value) {
      GetInfoApi();
    }
  };

  const interchangeFunc = (password: string) => {
    const params = getFieldsValueRecharge();
    params['payment'] = password;
    interchangeApi(params)
      .then((res) => {
        Modal.success({
          content: res.msg,
        });
      })
      .catch((msg) => {
        Modal.error({
          content: '转账失败' + msg,
        });
      });
  };
</script>

<style scoped lang="less">
  .ant-card + .ant-card {
    margin-top: 16px;
  }

  .blue-title {
    color: #40a9ff;
    font-weight: bold;
  }
</style>
